<template>
  <basic-container
    page-title="解析设置"
    back
    :sub-title="domain.name"
    custom-content
  >
    <template #filter>
      <div class="flex items-center justify-between filter">
        <div class="flex items-center filter-left gap-x-4">
          <el-button type="primary" @click="openEditRecordDialog()">
            添加记录
          </el-button>
          <el-select
            v-model="queryParams.type"
            class="w-[130px]"
            placeholder="请选择类型"
          >
            <el-option label="全部类型" value=""></el-option>
            <el-option
              v-for="item in recordTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
          <el-input
            v-model="searchKeyword"
            class="w-[360px] search-input"
            clearable
            :placeholder="placeholder"
          >
            <template #prepend>
              <el-select
                v-model="activeSearchType"
                placeholder="请选择"
                class="w-[100px]"
              >
                <el-option
                  v-for="item in searchTypeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </template>
            <template #append>
              <el-button :icon="Search" @click="handleSearch" />
            </template>
          </el-input>
        </div>
      </div>
    </template>

    <el-table
      v-loading="loading"
      :data="tableData"
      height="100%"
      class="basic-table"
      :tooltip-options="{ popperClass: 'basic-tooltip' }"
      @sort-change="handleSortChange"
    >
      <template #empty><TableEmpty /></template>
      <el-table-column
        type="index"
        width="80"
        label="序号"
        fixed="left"
      ></el-table-column>
      <el-table-column show-overflow-tooltip label="主机记录" min-width="150">
        <template #default="{ row }">
          <span v-format-table-cell="row.name"></span>
        </template>
      </el-table-column>
      <el-table-column label="记录类型" min-width="150">
        <template #default="{ row }">
          <span v-format-table-cell="row.type"></span>
        </template>
      </el-table-column>
      <!--
        <el-table-column prop="line" label="解析请求来源" min-width="140">
        <template #default="{ row }">
          {{ getOptionsLabel(lines, row.line) }}
        </template>
      </el-table-column>
      -->
      <el-table-column label="记录值" min-width="200" show-overflow-tooltip>
        <template #default="{ row }">
          <span v-format-table-cell="row.value"></span>
        </template>
      </el-table-column>
      <el-table-column label="TTL" min-width="100">
        <template #default="{ row }">
          <span v-format-table-cell="getOptionsLabel(ttlOpts, row.ttl)"></span>
        </template>
      </el-table-column>
      <el-table-column label="状态" width="100">
        <template #default="{ row }">
          <record-status :status="row.status"></record-status>
        </template>
      </el-table-column>
      <!-- <el-table-column
        prop="created_at"
        sortable="custom"
        label="添加时间"
        min-width="180"
      >
        <template #default="{ row }">
          <span v-format-unix="row.created_at"></span>
        </template>
      </el-table-column> -->

      <el-table-column label="备注" min-width="220">
        <template #default="{ row }">
          <basic-edit-table-remark
            :content="row.remark"
            :submit="value => handleEditRemark(row, value)"
          />
        </template>
      </el-table-column>
      <el-table-column
        prop="updated_at"
        sortable="custom"
        label="更新时间"
        min-width="180"
      >
        <template #default="{ row }">
          <span v-format-unix="row.updated_at"></span>
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="140" fixed="right">
        <template #default="{ row }">
          <div class="flex items-center gap-x-4">
            <el-link
              type="primary"
              :underline="false"
              @click="openEditRecordDialog(row)"
            >
              修改
            </el-link>
            <el-link
              type="primary"
              :underline="false"
              @click="handleUpdateRecordState(row)"
            >
              {{ row.status === E_YN.Y ? '暂停' : '启用' }}
            </el-link>
            <el-link
              type="danger"
              :underline="false"
              @click="handleDelete(row)"
            >
              删除
            </el-link>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <template #footer>
      <basic-pagination
        :pagination="pagination"
        @change="getList()"
      ></basic-pagination>
    </template>
  </basic-container>

  <edit-domain-record-dialog
    v-model:visible="editRecord.visible"
    v-model:loading="editRecord.loading"
    :record="editRecord.record"
    @reload="getList"
  ></edit-domain-record-dialog>
</template>

<script setup lang="ts">
import { Search } from '@element-plus/icons-vue'

import type { CommonParams } from '@/apis/model/_utils'
import type { DomainRecordModel } from '@/apis/model/domain'
import { BasicContainer } from '@/components/application'
import { RecordStatus } from '@/components/business'
import { E_YN } from '@/config/enums/base'
import { recordTypeOptions, ttlOpts } from '@/config/enums/record'
import { useListRequest } from '@/hooks/useListRequest'
import { getOptionsLabel } from '@/utils'
import ToastUtils from '@/utils/toast'

import EditDomainRecordDialog from './dialogs/EditDomainRecordDialog.vue'
import type { Domain } from './types'

type IQuery = Omit<
  CommonParams<'/v1/rr', 'get'>,
  'offset' | 'limit' | 'order' | 'sort'
>

const route = useRoute()
const domain = reactive<Domain>({
  id: route.params.id as string,
  name: route.query.name as string
})

/**
 * 查询参数
 */
const queryParams = reactive<IQuery & SortCustomParams>({
  domain_id: domain.id,
  // @ts-ignore
  type: '',
  name: '',
  value: '',
  sort: null,
  order: null
})

/**
 * 多类型搜索
 */
const searchTypeOptions = [
  { label: '主机记录', value: 'name' },
  { label: '记录值', value: 'value' }
]

const { activeSearchType, searchKeyword, placeholder } = useMultipartSearch(
  searchTypeOptions,
  queryParams
)

watch(
  () => queryParams.type,
  () => handleSearch()
)

function handleSortChange(params: SortParams) {
  const { sort, order } = getSortValue(params)
  queryParams.sort = sort!
  queryParams.order = order!
  pagination.page = 1
  getList()
}

/**
 * 列表数据
 */
const {
  data: tableData,
  getList,
  loading,
  pagination
} = useListRequest(domainRecordListApi, queryParams)
onMounted(getList)

/**
 * 搜索
 */
const handleSearch = () => {
  pagination.page = 1
  getList()
}

/**
 * 添加/修改解析记录
 */
const editRecord = reactive<CommonDialog>({
  visible: false,
  record: null,
  loading: false
})
const openEditRecordDialog = (record?: DomainRecordModel) => {
  editRecord.visible = true
  editRecord.record = record
}

const { setMessageBox } = useMessageBox()
/**
 * 删除
 */
const handleDelete = (row: DomainRecordModel) => {
  setMessageBox({
    isHtml: true,
    content:
      '<p>确认删除选中的解析记录？</p><p>解析记录变更后，可能不会立即生效。因为各地网络运营商 dns 存在缓存，在缓存未到期时，是不会向云解析 DNS 请求最新的解析记录，而是直接将之前缓存的解析结果返回给访问者，所以需要等待运营商刷新本地缓存后，解析才会实际生效。解析生效时间主要取决于运营商DNS缓存的解析记录的TTL到期时间，预计最快10-30分钟左右生效。如进行过DNS服务器名称修改，则一般需要24-48小时左右生效。</p>',
    title: '删除记录提示',
    async submit() {
      try {
        await deleteDomainRecordApi({ id: row.id! })
        decPageByData(pagination, tableData)
        getList()
        ToastUtils.success('删除成功')

        setMessageBox({ visible: false })
      } finally {
        setMessageBox({ loading: false })
      }
    }
  })
}

const handleEditRemark = async (row: DomainRecordModel, remark: string) => {
  await putDomainRecordApi({ id: row.id!, remark })
  getList()
  ToastUtils.success('修改成功')
}

/**
 * 修改解析记录状态
 */
const handleUpdateRecordState = async (row: DomainRecordModel) => {
  await putDomainRecordApi({
    ...row,
    id: row.id as string,
    status: row.status === E_YN.Y ? E_YN.N : E_YN.Y
  })
  getList()
  ToastUtils.success('修改成功')
}

/**
 * 依赖注入
 */
provide('domain', domain)
</script>

<style scoped lang="scss"></style>
